package com.jbt.mds.obdsdk

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Process
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.jbt.mds.sdk.diagnosis.dtc.Dtc
import com.jbt.mds.sdk.model.DataStreamInfo
import com.jbt.mds.sdk.obd.AbortCode
import com.jbt.mds.sdk.obd.BaseDetector
import com.jbt.mds.sdk.obd.IObdDetector
import com.jbt.mds.sdk.obd.ObdDetector
import com.jbt.mds.sdk.obd.ObdResource
import java.util.concurrent.atomic.AtomicBoolean


class MainActivity2 : AppCompatActivity() ,PermissionInterface, IObdDetector{
    private val TAG = "Obdljzt"
    lateinit var homeFragment: HomeFragment
    lateinit var  fragment2:Fragment
    lateinit var detectionHistoryFragment: DetectionHistoryFragment
    lateinit  var mObdDetector:ObdDetector
    lateinit var mObdResource: ObdResource
    var index = 0
    private var vin="";

    // 优先扫描的协议类型。
    private var priorProtocol = ""
    // 车辆类型 0 汽油车， 1 非汽油车型，包括柴油车、新能车等各类能源车型
    private var vehicleType = 1
    lateinit var  manager: FragmentManager
    lateinit var  transaction: FragmentTransaction
    lateinit var mPermissionHelper:PermissionHelper


    private val checkFinish =  AtomicBoolean(false)


    @SuppressLint("LongLogTag")
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        Singleton.initialize(this,this);
        mObdDetector = Singleton.getObdDetector();

        val ll1 = findViewById<View>(R.id.bottom_LinearLayout1)
        val iv1 = findViewById<ImageView>(R.id.iv1)
        val t1 = findViewById<TextView>(R.id.tv1)
        mPermissionHelper = PermissionHelper(this, this)
        mPermissionHelper.requestPermissions()
        val ll2 = findViewById<View>(R.id.bottom_LinearLayout2)
        val iv2 = findViewById<ImageView>(R.id.iv2)
        val t2 = findViewById<TextView>(R.id.tv2)

        val ll3 = findViewById<View>(R.id.bottom_LinearLayout3)
        val iv3 = findViewById<ImageView>(R.id.iv3)
        val t3 = findViewById<TextView>(R.id.tv3)
        manager = supportFragmentManager
        transaction = manager.beginTransaction()

        homeFragment = HomeFragment()
        fragment2 = UserFragment()
        detectionHistoryFragment = DetectionHistoryFragment()

        initial()
        fragmentHide()
        transaction.show(homeFragment)
        transaction.commit()


        ll1.setOnClickListener {
            if(index!=0){
                index = 0
                iv1.setImageResource(R.drawable.ac0)
                t1.setTextColor(resources.getColor(R.color.black))

                iv2.setImageResource(R.drawable.wd1)
                t2.setTextColor(resources.getColor(R.color.gray))
                iv3.setImageResource(R.drawable.ls1)
                t3.setTextColor(resources.getColor(R.color.gray))
                showFragment(homeFragment)
            }

        }

        ll2.setOnClickListener {
            if(index!=2){
                index = 2
                iv2.setImageResource(R.drawable.wd0)
                t2.setTextColor(resources.getColor(R.color.black))
                iv1.setImageResource(R.drawable.ac1)
                t1.setTextColor(resources.getColor(R.color.gray))
                iv3.setImageResource(R.drawable.ls1)
                t3.setTextColor(resources.getColor(R.color.gray))
                showFragment(fragment2)
            }

        }

        ll3.setOnClickListener {
            if(index!=1){
                index = 1
                iv3.setImageResource(R.drawable.ls0)
                t3.setTextColor(resources.getColor(R.color.black))
                iv1.setImageResource(R.drawable.ac1)
                t1.setTextColor(resources.getColor(R.color.gray))
                iv2.setImageResource(R.drawable.wd1)
                t2.setTextColor(resources.getColor(R.color.gray))
                showFragment(detectionHistoryFragment)
            }

        }
    }
    private fun initial() {
        transaction.add(R.id.framelayout, homeFragment)
        transaction.add(R.id.framelayout, fragment2)
        transaction.add(R.id.framelayout, detectionHistoryFragment)
    }

    private fun showFragment(fragment: Fragment) {
        transaction = manager.beginTransaction()
        fragmentHide()
        transaction.show(fragment)
        transaction.commit()
    }

    private fun fragmentHide() {
        transaction.hide(homeFragment)
        transaction.hide(fragment2)
        transaction.hide(detectionHistoryFragment)
    }

    override fun onDestroy() {
        ObdDetector.getInstance().disconnectVci()
        // 移除 Process.killProcess(Process.myPid()) 避免在正常退出时杀死进程
        super.onDestroy()
    }

    private var isScan13400 = false

    //当 Activity 变得可见（但尚未可交互）时调用。
    override fun onStart() {
        super.onStart()

        //开始检测汽油车型 初始化检测资源
        vehicleType = 1 // 0 为汽油车型， 1 为柴油车型

        priorProtocol = "";
        isScan13400 = false // 是否要扫描 13400 协议, true 为要扫描， false 为不扫描

        mObdDetector.startObdDetector(vehicleType, priorProtocol, isScan13400)





    }
    override fun getPermissionsRequestCode(): Int {
        return 10000
    }

    override fun getPermissions(): Array<String> {
        return arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }

    override fun requestPermissionsSuccess() {
        Log.i(TAG, "requestPermissionsSuccess:  授权成功， 可以正常使用")
    }

    override fun requestPermissionsFail() {
        Log.i(
            TAG,
            "requestPermissionsFail: 授权失败！请把定位、存储等权限授权给应用， 否则无法使用"
        )
    }
    /**
     * 检测资源初始化完毕, 可以开始检测了..
     */
     fun obdDiagnosisInitFinish() {
        Log.i(TAG, "obdDiagnosisInitFinish")

        // 使用上一次检测 成功激活的 OBD 通讯协议作为优先扫描协议
        //priorProtocol = mObdDetector.getVehicleProtocol();
        // 从协议选择列表中选择优先扫描的协议
        priorProtocol = BaseDetector.mProtocolData[6]
        val isScan13400 = false // 是否要扫描 13400 协议, true 为要扫描， false 为不扫描

        // priorProtocol 优先扫描的协议，协议数据从 mObdDetector.mProtocolData 中选择 或 以前激活成的数据中获取
        // vehicleType = 0 汽油车型，vehicleType = 1 柴油车型，
        //mObdDetector.startTest(vehicleType, priorProtocol);
        //mObdDetector.startTest(vehicleType);
        mObdDetector.startObdDetector(vehicleType, priorProtocol, isScan13400)
        Toast.makeText(this@MainActivity2, "资源初始化完成", Toast.LENGTH_SHORT).show()

    }




    //拿到初始化状态
    fun getCheckStatus():Boolean{
        return checkFinish.get()
    }

    /**
     * 当产生这个回调, 说明已激活成功, 然后可以读取所需的数据
     */
    override fun activeSuccess() {
        checkFinish.set(true)
        Log.i(TAG, "activeSuccess: 成功激活, 可以读取所需的数据了")

        mObdDetector.startReadRealDataStream()

//        vehicleType = 1
////        obdDiagnosisInitFinish()
//        priorProtocol = BaseDetector.mProtocolData[6]
//        isScan13400 = false // 是否要扫描 13400 协议, true 为要扫描， false 为不扫描
//
//        mObdDetector.startEmissionDetector(vehicleType, priorProtocol, isScan13400)

        

//        // 使用上一次检测 成功激活的 OBD 通讯协议作为优先扫描协议
//        //priorProtocol = mObdDetector.getVehicleProtocol();
//        // 从协议选择列表中选择优先扫描的协议
//        priorProtocol = BaseDetector.mProtocolData[6]
//        val isScan13400 = false // 是否要扫描 13400 协议, true 为要扫描， false 为不扫描
//
//        // priorProtocol 优先扫描的协议，协议数据从 mObdDetector.mProtocolData 中选择 或 以前激活成的数据中获取
//        // vehicleType = 0 汽油车型，vehicleType = 1 柴油车型，
//        //mObdDetector.startTest(vehicleType, priorProtocol);
//        //mObdDetector.startTest(vehicleType);
//        mObdDetector.startObdDetector(vehicleType, priorProtocol, isScan13400)
//        Toast.makeText(this@MainActivity2, "资源初始化完成", Toast.LENGTH_SHORT).show()
//
//
//        Log.i(TAG, "activeSuccess: 成功激活, 可以读取所需的数据了")
//
//        // 当前车辆的OBD协议， 可以保存起来， 以便在以后的检测中， 作为优先扫描协议使用
//        val vehcileProtocol = mObdDetector.vehicleProtocol
//        Log.i(
//           TAG,
//            "activeSuccess: 成功激活, 该车的OBD协议为：$vehcileProtocol"
//        )
//        checkFinish.set(true)
//        Toast.makeText(this@MainActivity2, "成功激活, 可以读取所需的数据了", Toast.LENGTH_LONG)
//            .show()
    }
    override fun abortError(abortCode: AbortCode) {
        Log.i(TAG, "abortError abortCode:$abortCode")

        Toast.makeText(this, "检测出错，错误代码：$abortCode", Toast.LENGTH_SHORT).show()
    }

    override fun stopFinish() {
        Log.i(TAG, "stopFinish:")
        Toast.makeText(this, "结束检测操作完成", Toast.LENGTH_LONG).show()
    }

    /**
     * 环保检测过程中, Float刷新产生的回调
     *
     * @param dataStreamInfo
     */
    override fun updateDataStream(dataStreamInfo: DataStreamInfo) {

        //updateDataStream:DataStreamInfo{strID='00077000', strCaption='MIL(故障指示灯)点亮后的运行时间(min)', strUnit=' min', strValue='0', showNum='0118'}
        Log.i(TAG, "updateDataStream:$dataStreamInfo")

        (homeFragment as HomeFragment).updateDataStream(dataStreamInfo)

    }

    /**
     * 环保检测过程中, 实时监控故障码产生的回调
     *
     * @param realDtcs
     */
    override fun updateRealDtc(realDtcs: List<Dtc>) {
        for (realDtc in realDtcs) {
            Log.i(TAG, "updateRealDtc: $realDtc")
        }
        Toast.makeText(this@MainActivity2, "数据持续更新中...", Toast.LENGTH_SHORT).show()
    }


    override fun updateRealFreezeFrameDataStream(p0: MutableList<DataStreamInfo>?) {

    }

    override fun updateVciConnectedState(vciConnectState: Int) {
        Log.i(TAG,
            "updateVciConnectedState: vciConnectState：$vciConnectState"
        )
        Toast.makeText(this, "蓝牙连接状态：$vciConnectState", Toast.LENGTH_SHORT)
            .show()
    }


    override fun scanProgress(currentTask: String?, progress: Int) {
        Log.i(TAG, "scanProgress: currentTask: " + currentTask + " progress:" + progress);
        
        // 通知HomeFragment更新扫描进度
        if (::homeFragment.isInitialized) {
            homeFragment.updateScanProgress(currentTask, progress)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK){
            if (requestCode == HomeFragment.CAMERA_IMAGE_REQ_CODE) {
                homeFragment.updateImageList(data)
            }
        }
    }
}